import { defineStore } from 'pinia'
import type { Sku, Spu } from '@/api/mall/product/spu'

export type CartItem = {
  skuId: number
  spuId: number
  name: string
  picUrl?: string
  price: number
  quantity: number
}

const STORAGE_KEY = 'pc-mall-cart'

function loadCart(): CartItem[] {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? (JSON.parse(raw) as CartItem[]) : []
  } catch {
    return []
  }
}

function saveCart(items: CartItem[]) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
}

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: loadCart() as CartItem[]
  }),
  getters: {
    totalCount: (s) => s.items.reduce((sum, i) => sum + i.quantity, 0),
    totalPrice: (s) => s.items.reduce((sum, i) => sum + i.price * i.quantity, 0)
  },
  actions: {
    add(spu: Spu, sku: Sku | null, quantity = 1) {
      const skuId = sku?.id || spu.id || 0
      const price = (sku?.price ?? spu.price ?? 0) as number
      const name = sku?.name || spu.name || ''
      const picUrl = sku?.picUrl || spu.picUrl
      const existing = this.items.find((i) => i.skuId === skuId)
      if (existing) {
        existing.quantity += quantity
      } else {
        this.items.push({ skuId, spuId: (spu.id as number) || 0, name, picUrl, price, quantity })
      }
      saveCart(this.items)
    },
    updateQuantity(skuId: number, quantity: number) {
      const it = this.items.find((i) => i.skuId === skuId)
      if (!it) return
      it.quantity = Math.max(1, quantity)
      saveCart(this.items)
    },
    remove(skuId: number) {
      this.items = this.items.filter((i) => i.skuId !== skuId)
      saveCart(this.items)
    },
    clear() {
      this.items = []
      saveCart(this.items)
    }
  }
})